package com.si.anddos;


import com.si.anddos.dpadapters.AnddosDbAdapter;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;

/**
 * A class representing Account List activity in anddos application
 * @author Carlos Martinez
 *
 */

public class AccountListActivity extends OptionsMenuActivity {
	private static final int ACTIVITY_CREATE=0;
	private static final int ACTIVITY_DETAIL=1;
	
    private AnddosDbAdapter mDbHelper;
    private ListView listAccounts;
    
    private long accountId;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.account_list);
        setTitle(R.string.titleAccountList);
        
        // onClickListener for list of accounts - starts New account activity
        // with Intent object with rowID of selected account
        listAccounts = (ListView) findViewById(R.id.listAccounts);
        listAccounts.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            	 
            	 Intent i = new Intent(parent.getContext(), AccountDetailActivity.class);
                 i.putExtra(AnddosDbAdapter.colAccountID, id);
                 startActivityForResult(i, ACTIVITY_DETAIL);
                 
            }
          });
        
        // filling the list from database
        mDbHelper = new AnddosDbAdapter(this);
        
        fillData();
        
        // register context menu for list of accounts
        registerForContextMenu(listAccounts);
    }

    private void fillData() {
        // Get all of the rows from the database and create the item list
    	mDbHelper.open();
        Cursor accountsCursor = mDbHelper.getAllAccounts();
        startManagingCursor(accountsCursor);

        // Create an array to specify the fields we want to display in the list (only TITLE)
        String[] from = new String[]{AnddosDbAdapter.colAccountUsername, AnddosDbAdapter.colAccountService};

        // and an array of the fields we want to bind those fields to 
        int[] to = new int[]{R.id.textAccountRow, R.id.textAccountRowService};

        // Now create a simple cursor adapter and set it to display
        SimpleCursorAdapter accounts = 
            new SimpleCursorAdapter(this, R.layout.account_list_row, accountsCursor, from, to);
        
        // make message to user if no accounts is in database
        if(accounts.getCount()==0)
        	Toast.makeText(this, R.string.textNoAccounts, Toast.LENGTH_SHORT).show();
        listAccounts.setAdapter(accounts);
   
        mDbHelper.close();
    }

    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        // add new menu item to Options menu - other items are defined in OptionsMenuActivity
        menu.add(0, Globals.NEWACCOUNT_ID, 0, R.string.menuNewAccount).setIcon(android.R.drawable.ic_menu_add);
        return true;
    }

    @Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) {
    	//handling click to new account menu item
        switch(item.getItemId()) {
            case Globals.NEWACCOUNT_ID:
                createAccount();
                return true;
        }

        return super.onMenuItemSelected(featureId, item);
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,
            ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        // create context menu for delete account
        menu.add(0, Globals.DELETEACCOUNT_ID, 0, R.string.menuDeleteAccount);
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
    	//handling click to delete account
        switch(item.getItemId()) {
            case Globals.DELETEACCOUNT_ID:
	        	AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
	        	accountId = info.id;
            	createAlertDeleteAccount();
                
                return true;
        }
        return super.onContextItemSelected(item);
    }

    private void createAccount() {
    	// start new account activity for result
        Intent i = new Intent(this, AccountNewActivity.class);
        startActivityForResult(i, ACTIVITY_CREATE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
    	super.onActivityResult(requestCode, resultCode, intent);
    	// refill data when goes back from new account activity and cancel button was not pressed
    	if(resultCode != RESULT_CANCELED)
    		fillData();
    }
    
    private void createAlertDeleteAccount()
    {
    	// create alert dialog to prevent the deletion of downloads that are linked to this account
    	AlertDialog.Builder builder = new AlertDialog.Builder(this);
    	builder.setTitle(R.string.alertDeleteAccountTitle)
    		   .setMessage(R.string.alertDeleteAccountMessage)
    	       .setCancelable(false)
    	       .setPositiveButton(R.string.alertDeletePosButton, new DialogInterface.OnClickListener() {
    	           public void onClick(DialogInterface dialog, int id) {
    	                // delete account in database and refill data from database
    	        	   mDbHelper.open();
    	               mDbHelper.deleteAccount(accountId);
    	               mDbHelper.close();
    	               fillData();
    	           }
    	       })
    	       .setNegativeButton(R.string.alertDeleteNegButton, new DialogInterface.OnClickListener() {
    	           public void onClick(DialogInterface dialog, int id) {
    	                dialog.cancel();
    	           }
    	       });
    	AlertDialog alert = builder.create();
    	alert.show();
    }
    
}


